package com.twq.patternmatch.pattern

import com.twq.patternmatch.basic._

/**
 * Created by tangweiqun on 2017/11/22.
 * 模式的守卫
 */
object PatternsGuards {
  def main(args: Array[String]): Unit = {
    //表达式为 x + x
    BinOp("+", Var("x"), Var("x")) //我们可以转换为:
    //x * 2
    BinOp("*", Var("x"), Number(2))

  }

  def simplifyAdd(e: Expr) = e match {
    case BinOp("+", a, b) if a == b => BinOp("*", b, Number(2))
    case _ => e
  }

  def guard(s: Any) = s match {
    case n: Int if 0 < n =>
    case s: String if s(0) == 'a' =>
  }

  //pattern overlaps
  def simplifyBad(expr: Expr): Expr = expr match {
    case UnOp(op, e) => UnOp(op, simplifyBad(e))
    case UnOp("-", UnOp("-", e)) => e //unreachable code
  }
}
